package pathways;

/**
 * Title:        Pathways
 * Description:  Pure Java version of the Pathways Project.
 * Copyright:    Copyright (c) 2002
 * Company:      Ants Technologies
 * @author Veejay Sani
 * @version 1.0
 */

import java.awt.Shape;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.Vector;

public class CMouseListener implements MouseListener, MouseMotionListener {

  public CMouseListener() {
    items = new Vector();
  }

  public void addItem(IListenableItem item)
  {
    items.add(item);
  }

  public void mouseClicked(MouseEvent e)
  {
    IListenableItem item = getItemUnderFocus(e);

    if (item != null)
    {
      item.eventOccurred("mouseClicked",e);
    }
  }

  public void mousePressed(MouseEvent e)
  {
    IListenableItem item = getItemUnderFocus(e);
    lockedItem = item;

    if (item != null)
    {
      item.eventOccurred("mousePressed",e);
    }
  }

  public void mouseReleased(MouseEvent e)
  {
    IListenableItem item = getItemUnderFocus(e);
    lockedItem = item;

    if (item != null)
    {
      item.eventOccurred("mouseReleased",e);
    }
  }

  public void mouseEntered(MouseEvent e)
  {
    IListenableItem item = getItemUnderFocus(e);

    if (item != null)
    {
      item.eventOccurred("mouseEntered",e);
    }
  }

  public void mouseExited(MouseEvent e)
  {
    IListenableItem item = getItemUnderFocus(e);

    if (item != null)
    {
      item.eventOccurred("mouseExited",e);
    }
  }

  public void mouseDragged(MouseEvent e)
  {
    IListenableItem item = null;

    // if no lock then get new item else use locked item
    if (lockedItem == null)
      item = getItemUnderFocus(e);
    else
      item = lockedItem;

    if (item != null)
    {
      item.eventOccurred("mouseDragged",e);
    }
  }

  public void mouseMoved(MouseEvent e)
  {
    IListenableItem item = getItemUnderFocus(e);

    if (item != null)
    {
      item.eventOccurred("mouseMoved",e);
    }
  }

  private IListenableItem getItemUnderFocus(MouseEvent e)
  {
    IListenableItem item;
    Shape s;

    for (int i = 0; i<items.size(); i++)
    {
      item = (IListenableItem)items.get(i);

      if (item.isVisible())
      {
        s = item.getShape();

        //if (e.getX() >= r.x && e.getX() <= (r.x + r.width)
        //    && e.getY() >= r.y && e.getY() <= (r.y + r.height))
        if (s.contains(e.getPoint()))
        {
          return item;
        }
      }
    }

    return null;
  }

  public Vector getItems()
  {
    return items;
  }

  private Vector items;
  private IListenableItem lockedItem; // useful for drag event
}